module.exports = () => {
  return async (ctx, next) => {
    const { app, socket } = ctx;
    const token = socket.handshake.query.token;

    try {
      if (!token) {
        socket.emit('error', { msg: '缺少token' });
        return;
      }

      // 验证token
      const decode = app.jwt.verify(token, app.config.jwt.secret);
      
      // 保存用户信息到socket
      socket.userId = decode.user_id;
      socket.userInfo = decode;

      // 将socket存储到app中,用于后续推送消息
      if (!app.io.userSockets) {
        app.io.userSockets = new Map();
      }
      app.io.userSockets.set(decode.user_id, socket);

      console.log(`用户 ${decode.user_id} 已连接 WebSocket`);

      await next();

      // 断开连接时清理
      socket.on('disconnect', () => {
        app.io.userSockets.delete(decode.user_id);
        console.log(`用户 ${decode.user_id} 已断开 WebSocket`);
      });
    } catch (error) {
      console.error('WebSocket认证失败:', error);
      socket.emit('error', { msg: 'token验证失败' });
    }
  };
};

